<template>
  <div>
    <div class="login">
      <div class="title">登录后更优惠</div>
      <van-form class="form" ref="from">
        <van-field v-model="username" label="手机号" placeholder="输入手机号" type="tel" @input="changeUserName" :rules="[{ required: true, pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入有效手机号' }]" />
        <van-field v-model="password" label="验证码" placeholder="输入验证码" type="digit" maxlength="4" :rules="[{ required: true, message: '请输入验证码' }]">
          <template #button>
            <van-button color="#ff3030" plain size="small" @click="getCode" :disabled="!canGetcode">
              <van-count-down ref="countDown" :time="time" :auto-start="false" @finish="finish">
                <template v-slot="timeData">
                  <span v-if="!showCountDown" class="seconds">获取验证码</span>
                  <span v-else class="seconds">{{ timeData.seconds }}秒后重新获取</span>
                </template>
              </van-count-down>
            </van-button>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button color="#ff3030" block type="info" native-type="submit" @click="login">登录</van-button>
        </div>
      </van-form>
      <van-divider>说明</van-divider>
      <div style="color: #bbb;">验证码短信开头为【xyy之家】</div>
    </div>
  </div>
</template>

<script>
import { Form, Field, Button, Divider, CountDown } from "vant";

export default {
  name: "Home",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Divider.name]: Divider,
    [CountDown.name]: CountDown
  },
  data() {
    return {
      username: "",
      password: "",
      canGetcode: false,
      showCountDown: false,
      time: 60 * 1000
    };
  },
  mounted: function() {
    let vm = this;
    this.$nextTick(function() {
      // vm.$cookies.set('token','default', "1y");
      // console.log(vm.$cookies.keys())
    });
  },
  methods: {
    login() {
      let vm = this;
      vm.$ajax
        .post("/login", { mobile: vm.username, code: vm.password })
        .then(function(r) {
          vm.$cookies.set("token", r.data.token, "1y");
          vm.$toast("登录成功");
          vm.$router.push("/home/user")
        });
    },
    getCode() {
      let vm = this;
      vm.$ajax.get("/getCode?mobile=" + vm.username).then(function(r) {
        vm.$toast("验证码已发送");
        vm.canGetcode = false;
        vm.$refs.countDown.start();
        vm.showCountDown = true;
      });
    },
    finish() {
      this.canGetcode = true;
      this.showCountDown = false;
      this.$refs.countDown.reset();
    },
    changeUserName(str) {
      if (/^[1]([3-9])[0-9]{9}$/.test(str)) {
        this.canGetcode = true;
      }
    }
  }
};
</script>

<style scoped>
.login {
  padding: 30% 10px 10px 10px;
}

.login .title {
  text-align: center;
  font-size: 30px;
  margin: 20px;
}

.login .form div {
  margin-bottom: 20px;
}
.seconds {
  color: rgb(255, 48, 48);
  line-height: 30px;
  font-size: 12px;
}
</style>